<template>
  <div class="user-profile-container">
    <h1>个人中心</h1>
    
    <div class="profile-card">
      <h2>个人信息</h2>
      <div v-if="loading" class="loading">加载中...</div>
      <div v-else class="profile-info">
        <div class="info-item">
          <strong>用户名:</strong> {{ user.username }}
        </div>
        <div class="info-item">
          <strong>邮箱:</strong> {{ user.email }}
        </div>
        <div class="info-item">
          <strong>注册时间:</strong> {{ formatDate(user.createdAt) }}
        </div>
      </div>
    </div>
    
    <div class="data-management-card">
      <h2>数据管理</h2>
      <div class="data-stats" v-if="stats">
        <div class="stat-item">
          <span class="stat-label">文档数量:</span>
          <span class="stat-value">{{ stats.documents || 0 }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">卡片数量:</span>
          <span class="stat-value">{{ stats.cards || 0 }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">学习路径:</span>
          <span class="stat-value">{{ stats.learningPaths || 0 }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">书签数量:</span>
          <span class="stat-value">{{ stats.bookmarks || 0 }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">笔记数量:</span>
          <span class="stat-value">{{ stats.notes || 0 }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">学习进度:</span>
          <span class="stat-value">{{ stats.progress || 0 }}</span>
        </div>
      </div>
      
      <div class="data-cleanup-section">
        <h3>数据清理</h3>
        <p class="warning-text">请谨慎操作，以下操作将永久删除相关数据，无法恢复！</p>
        
        <div class="cleanup-options">
          <div class="cleanup-option">
            <button 
              class="cleanup-btn" 
              @click="cleanupData('bookmarks')"
              :disabled="cleanupInProgress"
            >
              清空书签
            </button>
            <span class="option-desc">删除所有收藏的卡片书签</span>
          </div>
          
          <div class="cleanup-option">
            <button 
              class="cleanup-btn" 
              @click="cleanupData('notes')"
              :disabled="cleanupInProgress"
            >
              清空笔记
            </button>
            <span class="option-desc">删除所有卡片笔记</span>
          </div>
          
          <div class="cleanup-option">
            <button 
              class="cleanup-btn" 
              @click="cleanupData('progress')"
              :disabled="cleanupInProgress"
            >
              清空学习进度
            </button>
            <span class="option-desc">删除所有学习路径的进度记录</span>
          </div>
          
          <div class="cleanup-option">
            <button 
              class="cleanup-btn danger" 
              @click="confirmFullCleanup"
              :disabled="cleanupInProgress"
            >
              清空所有数据
            </button>
            <span class="option-desc">删除所有文档、卡片、学习路径、进度记录、书签和笔记</span>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 确认对话框 -->
    <div class="modal" v-if="showConfirmDialog">
      <div class="modal-content">
        <h3>确认清空所有数据</h3>
        <p>此操作将永久删除您的所有数据，包括上传的文档、生成的卡片、学习路径、进度记录、书签和笔记。此操作无法撤销！</p>
        <p>请输入"DELETE"确认删除：</p>
        <input 
          type="text" 
          v-model="confirmText" 
          placeholder="输入DELETE确认" 
          class="confirm-input"
        />
        <div class="modal-actions">
          <button @click="showConfirmDialog = false" class="cancel-btn">取消</button>
          <button 
            @click="executeFullCleanup" 
            :disabled="confirmText !== 'DELETE'" 
            class="confirm-btn"
          >
            确认删除
          </button>
        </div>
      </div>
    </div>
    
    <!-- 结果提示 -->
    <div class="cleanup-result" v-if="cleanupResult">
      <h3>清理结果</h3>
      <pre>{{ JSON.stringify(cleanupResult, null, 2) }}</pre>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue';
import { useToast } from 'vue-toastification';
import { userApi, cleanupUserData, getUserStats } from '@/services/api';
import { useUserStore } from '@/store/user';

export default {
  name: 'UserProfileView',
  setup() {
    const userStore = useUserStore();
    const toast = useToast();
    
    const user = ref({});
    const loading = ref(true);
    const stats = ref(null);
    const cleanupInProgress = ref(false);
    const showConfirmDialog = ref(false);
    const confirmText = ref('');
    const cleanupResult = ref(null);
    
    // 获取用户信息
    const fetchUserProfile = async () => {
      try {
        loading.value = true;
        const response = await userApi.getProfile();
        user.value = response.data;
        
        // 获取用户统计数据
        await fetchUserStats();
      } catch (error) {
        console.error('获取用户信息失败:', error);
        toast.error('获取用户信息失败');
      } finally {
        loading.value = false;
      }
    };
    
    // 获取用户统计数据
    const fetchUserStats = async () => {
      try {
        const response = await getUserStats();
        stats.value = response.data;
      } catch (error) {
        console.error('获取用户统计数据失败:', error);
        toast.error('获取用户统计数据失败');
        
        // 设置默认值
        stats.value = {
          documents: 0,
          cards: 0,
          learningPaths: 0,
          bookmarks: user.value.bookmarks ? user.value.bookmarks.length : 0,
          notes: user.value.notes ? user.value.notes.length : 0,
          progress: 0
        };
      }
    };
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '未知';
      const date = new Date(dateString);
      return date.toLocaleDateString('zh-CN');
    };
    
    // 清理数据
    const cleanupData = async (dataType) => {
      try {
        cleanupInProgress.value = true;
        cleanupResult.value = null;
        
        // 非全量清理不需要确认对话框
        const response = await cleanupUserData(dataType);
        
        toast.success(`${getCleanupTypeName(dataType)}清理成功`);
        cleanupResult.value = response.data;
        
        // 重新获取用户信息
        await fetchUserProfile();
      } catch (error) {
        console.error('数据清理失败:', error);
        toast.error('数据清理失败');
      } finally {
        cleanupInProgress.value = false;
      }
    };
    
    // 显示全量清理确认对话框
    const confirmFullCleanup = () => {
      showConfirmDialog.value = true;
      confirmText.value = '';
    };
    
    // 执行全量清理
    const executeFullCleanup = async () => {
      if (confirmText.value !== 'DELETE') return;
      
      showConfirmDialog.value = false;
      
      try {
        cleanupInProgress.value = true;
        cleanupResult.value = null;
        
        const response = await cleanupUserData('all');
        
        toast.success('所有数据清理成功');
        cleanupResult.value = response.data;
        
        // 重新获取用户信息
        await fetchUserProfile();
      } catch (error) {
        console.error('数据清理失败:', error);
        toast.error('数据清理失败');
      } finally {
        cleanupInProgress.value = false;
      }
    };
    
    // 获取清理类型名称
    const getCleanupTypeName = (type) => {
      const types = {
        'bookmarks': '书签',
        'notes': '笔记',
        'progress': '学习进度',
        'all': '所有数据'
      };
      return types[type] || '数据';
    };
    
    onMounted(() => {
      fetchUserProfile();
    });
    
    return {
      user,
      loading,
      stats,
      cleanupInProgress,
      showConfirmDialog,
      confirmText,
      cleanupResult,
      formatDate,
      cleanupData,
      confirmFullCleanup,
      executeFullCleanup
    };
  }
};
</script>

<style scoped>
.user-profile-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

h1 {
  margin-bottom: 30px;
  color: #333;
  text-align: center;
}

.profile-card, .data-management-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 30px;
}

h2 {
  margin-top: 0;
  color: #333;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
  margin-bottom: 20px;
}

.loading {
  text-align: center;
  padding: 20px;
  color: #666;
}

.profile-info {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.info-item {
  display: flex;
  gap: 10px;
}

.data-stats {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 15px;
  margin-bottom: 30px;
}

.stat-item {
  background-color: #f5f5f5;
  border-radius: 6px;
  padding: 15px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.data-cleanup-section h3 {
  margin-top: 0;
  color: #333;
}

.warning-text {
  color: #e53935;
  font-weight: bold;
  margin-bottom: 20px;
}

.cleanup-options {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px;
}

.cleanup-option {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.cleanup-btn {
  padding: 10px 15px;
  border: none;
  border-radius: 4px;
  background-color: #f5f5f5;
  cursor: pointer;
  font-weight: bold;
  transition: background-color 0.2s;
}

.cleanup-btn:hover {
  background-color: #e0e0e0;
}

.cleanup-btn.danger {
  background-color: #ffebee;
  color: #c62828;
}

.cleanup-btn.danger:hover {
  background-color: #ffcdd2;
}

.cleanup-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.option-desc {
  font-size: 12px;
  color: #666;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  width: 90%;
  max-width: 500px;
}

.confirm-input {
  width: 100%;
  padding: 10px;
  margin: 15px 0;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.cancel-btn, .confirm-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-btn {
  background-color: #f5f5f5;
}

.confirm-btn {
  background-color: #e53935;
  color: white;
}

.confirm-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.cleanup-result {
  margin-top: 30px;
  background-color: #f5f5f5;
  border-radius: 8px;
  padding: 20px;
}

.cleanup-result pre {
  white-space: pre-wrap;
  word-break: break-word;
}
</style> 